package com.jxpanda.spring.module.auth.core;

import com.jxpanda.spring.module.auth.core.exception.StrategyNotFoundException;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OAuth2StrategyResolver<S extends OAuth2Strategy> {

    private final Map<String, S> strategyCache;

    public OAuth2StrategyResolver() {
        this(new HashMap<>());
    }

    public OAuth2StrategyResolver(Map<String, S> stringSMap) {
        this.strategyCache = stringSMap == null ? new HashMap<>() : stringSMap;
    }

    @SuppressWarnings("UnusedReturnValue")
    public OAuth2StrategyResolver<S> putStrategy(String clientId, S strategy) {
        this.strategyCache.put(clientId, strategy);
        return this;
    }


    protected Mono<S> selectStrategy(String clientId, String grantType) {
        S strategy = strategyCache.get(clientId);
        if (strategy != null && strategy.isSupport(grantType)) {
            return Mono.just(strategy);
        }
        return Mono.error(new StrategyNotFoundException("Unsupported clientId:" + clientId));
    }

}
